package top.hidoctor.auscultation.feature.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.common.StringUtils;
import com.tang.util.AppUtil;
import com.tang.util.BigDecimalUtil;
import com.tang.util.DensityUtil;
import com.tang.util.DialogUtil;
import com.tang.util.GsonUtil;
import com.tang.util.SPUtil;
import com.tang.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.ChooseAdapter2;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.base.Constant;
import top.hidoctor.auscultation.bean.DictionaryBean;
import top.hidoctor.auscultation.bean.PatientLocalInfo;
import top.hidoctor.auscultation.net.c.GatherContract;
import top.hidoctor.auscultation.net.p.GatherPresenter;
import top.hidoctor.auscultation.net.req.DictionaryReq;
import top.hidoctor.auscultation.utils.BlueToothUtils;
import top.hidoctor.auscultation.utils.BlueToothDataUtils;
import top.hidoctor.auscultation.utils.ConvertPcmToWav;
import top.hidoctor.auscultation.utils.HexUtil;
import top.hidoctor.auscultation.utils.MyInternalStorage;
import top.hidoctor.auscultation.view.EcgView;

import static top.hidoctor.auscultation.feature.activity.DeviceActivity.BLUETOOTH_DEVICE;
import static top.hidoctor.auscultation.utils.BlueToothUtils.getBlueToothUtils;

public class GatherActivity extends BaseActivity implements View.OnClickListener, GatherContract.View {

    private static final int WRITE_SUC = 0x001;
    private static final int WRITE_FAIL = 0x002;
    private static final int SWITCH_OFF = 0x003;
    private static final int ADD_LIST = 0x005;
    private TextView tvNumber, tvStatus;
    private View viewStatus;
    private BluetoothGatt bluetoothGatt;
    private Button btn;

    private AudioTrack tracker;

    private String order = "";
    private List<DictionaryBean.ResultBean> positionList = new ArrayList<>();
    private List<DictionaryBean.ResultBean> coordinateList = new ArrayList<>();
    private List<DictionaryBean.ResultBean> siteList = new ArrayList<>();

    // 暂存本地的数据
    private List<String> localList = new ArrayList<>();
    private ArrayList<Float> pointList = new ArrayList<>();//储存的点集合
    private boolean isRecord = false;
    private Chronometer chronometer;
    private AlertDialog dialog;
    private MyInternalStorage myInternal;
    private List<PatientLocalInfo> list = new ArrayList<>();
    private BlueToothUtils blueToothUtils;
    private String processedData = "";
    private boolean isUpdate = false;
    int pos = 0;
    private Timer pointTimer;
    private LinearLayout llEcg, llEcgContent;
    private Timer moveTimer;
    private GatherPresenter presenter;
    private DictionaryReq req;
    private TextView tiwei;
    private TextView peihe;
    private TextView changsuo;
    private AlertDialog chooseDialog;
    private ChooseAdapter2 chooseAdapter;
    private EditText shengao;
    private EditText tizhong;
    private EditText address;
    private String tiweiName, tiweiId, peiheName, peiheId, changsuoName, changsuoId, zhengjing = "0", shoushu = "0";
    private SegmentTabLayout tabZhenjing;
    private SegmentTabLayout tabShoushu;
    private float gap_x;// 心电图 每个坐标之间的距离px
    private int moveSize = 0;
    private HorizontalScrollView hScrollView;
    private TextView tvTitle;
    private TextView tvProgress;
    private boolean isEnd = false;
    private int miss = 0;// 计时

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_gather);
        initView();
        initEvent();

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initEvent() {
        //网络请求
        presenter = new GatherPresenter(this, this);
        req = new DictionaryReq();
        req.setGroupCode("SAMPLE_POSITION");
        presenter.getDictionary(req);
        req.setGroupCode("SAMPLE_COORDINATE");
        presenter.getDictionary(req);
        req.setGroupCode("SAMPLE_SITE");
        presenter.getDictionary(req);

        bufferQueue = new LinkedList<>();
//        // 初始化数据
        int bufferSize = AudioTrack.getMinBufferSize(frequency, channelOutConfig, audioEncoding);

        tracker = new AudioTrack(AudioManager.STREAM_MUSIC, frequency, channelOutConfig, audioEncoding, bufferSize * 2, AudioTrack.MODE_STREAM);//录音播放

        BluetoothDevice device = getIntent().getParcelableExtra(BLUETOOTH_DEVICE);

        if (device != null) {
//            tvNumber.setText(device.getName() + "\n" + device.getAddress());
            tvNumber.setText(device.getAddress());
            tvStatus.setText("在线");
            viewStatus.setBackground(getResources().getDrawable(R.drawable.green_point));
        } else {
            tvStatus.setText("离线");
            viewStatus.setBackground(getResources().getDrawable(R.drawable.red_point));
        }
        btn.setVisibility(View.VISIBLE);

        myInternal = new MyInternalStorage(this);


        //获取 本地数组文件
        String content = (String) SPUtil.get(GatherActivity.this, Constant.LOCAL_INFO, "");
        if (!TextUtils.isEmpty(content)) {
            list = GsonUtil.parseJson(content, new TypeToken<List<PatientLocalInfo>>() {
            });
        }
        blueToothUtils = getBlueToothUtils();
        blueToothUtils.setSetMtu(true);
        bluetoothGatt = blueToothUtils.connect(device, this);
        blueToothUtils.setBlueToothHandle(new BlueToothUtils.BlueToothHandle() {
            @Override
            public void getCharacteristicChanged(byte[] data) {

                //  这里将蓝牙传过来的数据转换为 16 进制格式的字符串
                if (data.length > 5) {
                    final byte[] bytes = Arrays.copyOfRange(data, 6, data.length - 2);
                    if (HexUtil.encodeHexStr(bytes).length() > 100) {
                        localList.add(HexUtil.encodeHexStr(bytes));
                    }
                    for (int i = 0; i < HexUtil.encodeHexStr(bytes).length() - 1; i += 4) {
                        Float point = BlueToothDataUtils.getComplement(HexUtil.encodeHexStr(bytes).substring(i, i + 4));
                        pointList.add(point);
                    }
                    String s = BlueToothDataUtils.transformData(HexUtil.encodeHexStr(bytes));
                    bufferQueue.offer(HexUtil.hexStringToBytes(s));
//                    Log.i("TAG", "处理后: " + HexUtil.encodeHexStr(bytes));
                } else {//
                    if (HexUtil.encodeHexStr(data).equals("ad0000ad00")) {//停止接受
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isRecord = false;
                                if (chronometer != null) {
                                    chronometer.stop();
                                }
                                if (pointTimer != null) {
                                    pointTimer.cancel();
                                }
                                if (moveTimer != null) {
                                    moveTimer.cancel();
                                }
                            }
                        }, 1000);
                    }
                }
            }

            @Override
            public void stateDisconnected() {
            }

            @Override
            public void stateDisconnecting() {

            }

            @Override
            public void stateConnected() {

            }

            @Override
            public void stateConnecting() {

            }

            @Override
            public void characteristicWrite(int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    mHandler.sendEmptyMessage(WRITE_SUC);
                } else {
                    mHandler.sendEmptyMessage(WRITE_FAIL);
                }
            }

            @Override
            public void startWrite() {

            }
        });
    }


    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFinish();
            }
        });
        tvNumber = findViewById(R.id.tv_number);
        tvTitle = findViewById(R.id.tv_title);
        tvStatus = findViewById(R.id.tv_status);
        viewStatus = findViewById(R.id.view_status);
        btn = findViewById(R.id.btn);
        chronometer = findViewById(R.id.chronometer);
        hScrollView = findViewById(R.id.h_scrollView);
        tvProgress = findViewById(R.id.tv_progress);
        llEcg = findViewById(R.id.ll_ecg);
        llEcgContent = findViewById(R.id.ll_ecg_content);
        btn.setOnClickListener(this);
        initDialog();
        //初始化dialog

        //设置网格背景
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        Bitmap bitmap = drawBackground(20, DensityUtil.dip2px(this, 140), displayMetrics.widthPixels - DensityUtil.dip2px(this, 40));
        hScrollView.setBackground(new BitmapDrawable(bitmap));

        int width = displayMetrics.widthPixels - DensityUtil.dip2px(this, 60);
        gap_x = (float) BigDecimalUtil.div(width, 370);
//        gap_x = (float) BigDecimalUtil.div(width, 15000);

        hScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                if (miss == 60) {//心音 一分钟后自动保存
                    isRecord = false;
                    miss = 0;
                    order = "ad00ad00";//结束录音
                    blueToothUtils.write(order);
                    myInternal.delete("temporary_content.pcm");
                    chronometer.stop();
                    if (pointTimer != null) {
                        pointTimer.cancel();
                    }
                    if (moveTimer != null) {
                        moveTimer.cancel();
                    }
                    disposeData();
                    return;
                }
                miss++;
                Log.i("TAG", "onChronometerTick: " + chronometer.getText().toString() + " " + miss);
            }
        });
        initEcgView();
    }

    /**
     * 初始化 心电图
     */
    private void initEcgView() {
        ArrayList<Float> list = new ArrayList();
        //初始化心电图
        for (int i = 0; i < 400; i++) {
//            for (int i = 0; i < 16000; i++) {
            list.add(0f);
        }
        addEcgView(list);
    }


    /**
     * 初始化弹窗
     */
    private void initDialog() {
        String[] choose = {"否", "是"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_save_content, null);
        builder.setView(dialogView);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);

        TextView tvCancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tvSave = dialogView.findViewById(R.id.tv_save);
        shengao = dialogView.findViewById(R.id.edit_shengao);
        tizhong = dialogView.findViewById(R.id.edit_tizhong);
        address = dialogView.findViewById(R.id.edit_address);
        tiwei = dialogView.findViewById(R.id.tv_tiwei);
        peihe = dialogView.findViewById(R.id.tv_peihe);
        changsuo = dialogView.findViewById(R.id.tv_changsuo);
        tabZhenjing = dialogView.findViewById(R.id.tab_zhenjing);
        tabShoushu = dialogView.findViewById(R.id.tab_shoushu);
        tabZhenjing.setTabData(choose);
        tabShoushu.setTabData(choose);
        tabZhenjing.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                zhengjing = position + "";
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        tabShoushu.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                shoushu = position + "";
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        tiwei.setOnClickListener(this);
        peihe.setOnClickListener(this);
        changsuo.setOnClickListener(this);
        tvSave.setOnClickListener(this);
        tvCancel.setOnClickListener(this);

    }


    /**
     * 选择体位 配合程度  采集场所
     *
     * @param type
     */
    private void showPick(final int type) {
        final List<String> list = new ArrayList<>();
        if (type == 1) {
            for (int i = 0; i < positionList.size(); i++) {
                list.add(positionList.get(i).getTitle());
            }
        } else if (type == 2) {
            for (int i = 0; i < coordinateList.size(); i++) {
                list.add(coordinateList.get(i).getTitle());
            }
        } else if (type == 3) {
            for (int i = 0; i < siteList.size(); i++) {
                list.add(siteList.get(i).getTitle());
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_choose, null);
        builder.setView(dialogView);
        chooseDialog = builder.create();
        chooseDialog.setCanceledOnTouchOutside(true);
        chooseDialog.show();
        chooseDialog.getWindow().setLayout(DensityUtil.dip2px(this, 240), DensityUtil.dip2px(this, 300));
        RecyclerView rc = dialogView.findViewById(R.id.rc);
        TextView tvTitle = dialogView.findViewById(R.id.tv_title);
        rc.setLayoutManager(new LinearLayoutManager(this));
        rc.setAdapter(chooseAdapter = new ChooseAdapter2(R.layout.item_choose, null));
        if (type == 1) {
            chooseAdapter.setNewData(positionList);
            tvTitle.setText("请选择：体位");
        } else if (type == 2) {
            chooseAdapter.setNewData(coordinateList);
            tvTitle.setText("请选择：配合程度");
        } else if (type == 3) {
            chooseAdapter.setNewData(siteList);
            tvTitle.setText("请选择：采集场所");
        }
        chooseAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (type == 1) {
                    for (int i = 0; i < positionList.size(); i++) {
                        positionList.get(i).setCheck(false);
                    }
                    positionList.get(position).setCheck(true);
                    tiwei.setText(positionList.get(position).getTitle());
                    tiweiName = positionList.get(position).getTitle();
                    tiweiId = positionList.get(position).getId();
                } else if (type == 2) {
                    for (int i = 0; i < coordinateList.size(); i++) {
                        coordinateList.get(i).setCheck(false);
                    }
                    coordinateList.get(position).setCheck(true);
                    peihe.setText(coordinateList.get(position).getTitle());
                    peiheName = coordinateList.get(position).getTitle();
                    peiheId = coordinateList.get(position).getId();
                } else if (type == 3) {
                    for (int i = 0; i < siteList.size(); i++) {
                        siteList.get(i).setCheck(false);
                    }
                    siteList.get(position).setCheck(true);
                    changsuo.setText(siteList.get(position).getTitle());
                    changsuoName = siteList.get(position).getTitle();
                    changsuoId = siteList.get(position).getId();
                }
                chooseAdapter.notifyDataSetChanged();
                chooseDialog.dismiss();
            }
        });
    }

    public static Bitmap drawBackground(int cellSize, int height, int widht) {
        Bitmap bitmap = Bitmap.createBitmap(widht, height, Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(bitmap);
        Paint background = new Paint();
        background.setColor(Color.WHITE);
        cv.drawRect(0, 0, widht, height, background);
        background.setAntiAlias(true);
        background.setColor(Color.parseColor("#cccccc"));
        for (int i = 0; i < widht / cellSize + 1; i++) {
            cv.drawLine(cellSize * i, 0, cellSize * i, height, background);
        }
        for (int i = 0; i < height / cellSize + 1; i++) {
            cv.drawLine(0, cellSize * i, widht, cellSize * i, background);
        }
        return bitmap;
    }

    /**
     * 点击事件
     * @param view
     */
    @SuppressLint("NewApi")
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn:
                if (btn.getText().equals("开始采集")) {
                    chronometer.setBase(SystemClock.elapsedRealtime());//计时器清零
                    chronometer.setFormat("%s");
                    //初始化心电图
                    llEcgContent.removeAllViews();
                    initEcgView();
                    moveSize = 0;
                    pointList.clear();
                    bufferQueue.clear();
                    order = "a600a600";//开始录音
                    isRecord = true;
                    showLoading();

                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            hideLoading();
                            new Thread(new RecordPlayingRunnable()).start();
                            //开启计时器
                            chronometer.start();
                        }
                    }, 1000);
                    startEcgView();
                    startTime();
                    blueToothUtils.write(order);
                } else {

                    miss = 0;
                    isRecord = false;
                    order = "ad00ad00";//结束录音
                    blueToothUtils.write(order);
                    myInternal.delete("temporary_content.pcm");
                    if (pointTimer != null) {
                        pointTimer.cancel();
                    }
                    if (moveTimer != null) {
                        moveTimer.cancel();
                    }
                    disposeData();
                }
                break;
            case R.id.btn_ai:
                if (!isEnd) {
                    order = "b700b700";//听诊引导AI点击
                } else {
                    order = "a200a200";//听诊引导结束
                }
                blueToothUtils.write(order);
                break;
            case R.id.tv_tiwei:
                if (!AppUtil.isFastClick()) {
                    hideSoft(tiwei);
                    showPick(1);
                }
                break;
            case R.id.tv_peihe:
                if (!AppUtil.isFastClick()) {
                    hideSoft(peihe);
                    showPick(2);
                }
                break;
            case R.id.tv_changsuo:
                if (!AppUtil.isFastClick()) {
                    hideSoft(changsuo);
                    showPick(3);
                }
                break;
            case R.id.tv_save:
                String shengao = this.shengao.getText().toString();
                String tizhong = this.tizhong.getText().toString();
                String tiwei = this.tiwei.getText().toString();
                String peihe = this.peihe.getText().toString();
                String changsuo = this.changsuo.getText().toString();
                String address = this.address.getText().toString();
                if (TextUtils.isEmpty(shengao)) {
                    showToast("请输入身高");
                    return;
                }
                if (TextUtils.isEmpty(tizhong)) {
                    showToast("请输入体重");
                    return;
                }
                if (TextUtils.isEmpty(tiwei)) {
                    showToast("请选择体位");
                    return;
                }
                if (TextUtils.isEmpty(peihe)) {
                    showToast("请选择配合程度");
                    return;
                }
                if (TextUtils.isEmpty(changsuo)) {
                    showToast("请选择采集场所");
                    return;
                }
                //保存文件到本地
                try {
                    String data = myInternal.get("temporary_content.pcm");
                    Log.i("TAG", "onClick: " + data);
                    //pcm 转 wav
                    final String path = getFilesDir().getAbsolutePath() + "/temporary_content.pcm";
                    long time = System.currentTimeMillis();
                    final String outpath = path.replace("temporary_content.pcm", "循音科技-" + time + ".wav");
                    BlueToothDataUtils.convertPCMFileToWAVFile(8000, (short) 1, (short) 16, outpath, HexUtil.hexStringToBytes(data));
                    if (!TextUtils.isEmpty(processedData)) {
                        myInternal.save("循音科技-" + time + ".pcm", data);
                    }
                    list.add(new PatientLocalInfo(
                            shengao, tizhong, tiweiName, tiweiId, peiheName, peiheId,
                            zhengjing, shoushu, changsuoName, changsuoId, address,
                            "循音科技-" + time + ".wav", "循音科技-" + time + ".pcm",
                            time, 1, BlueToothDataUtils.getDuration(outpath), "循音科技-" + time + ".wav"));
                    SPUtil.put(GatherActivity.this, Constant.LOCAL_INFO, GsonUtil.toJsonStr(list));
                    showToast("保存成功");
                    dialog.dismiss();
                    //初始化
                    this.shengao.setText("");
                    this.tizhong.setText("");
                    this.address.setText("");
                    for (DictionaryBean.ResultBean bean : positionList) {
                        bean.setCheck(false);
                    }
                    for (DictionaryBean.ResultBean bean : coordinateList) {
                        bean.setCheck(false);
                    }
                    for (DictionaryBean.ResultBean bean : siteList) {
                        bean.setCheck(false);
                    }
                    tabShoushu.setCurrentTab(0);
                    tabZhenjing.setCurrentTab(0);
                    this.tiwei.setText("");
                    this.peihe.setText("");
                    this.changsuo.setText("");

                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.tv_cancel:
                dialog.dismiss();
                break;
        }
    }

    /**
     * 开始 绘制动态心电图
     */
    private void startEcgView() {
        moveTimer = new Timer();
        moveTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                //速度
                double speed = BigDecimalUtil.div(BigDecimalUtil.mul(370, gap_x), 20.5);
//                double speed = BigDecimalUtil.div(BigDecimalUtil.mul(15000, gap_x), 20);
                hScrollView.smoothScrollTo((int) (speed * moveSize), 0);
                moveSize++;
            }
        }, 1000, 100);
    }

    private void startTime() {
        pointTimer = new Timer();
        pointTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (pointList.size() == 0) {
                    return;
                }
                pos++;
                Log.e("TAG", "run: " + pointList.size());
                Message message = mHandler.obtainMessage(ADD_LIST, pointList);
                mHandler.sendMessage(message);

            }
        }, 1000, 1000);
    }


    /**
     *   处理数据
     */

    private void disposeData() {
        if (localList.size() == 0) {
            return;
        }
        try {
            StringBuffer sb = new StringBuffer();
            // pcm 文件过度缓存
            for (int i = 0; i < localList.size(); i++) {
                if (localList.get(i) != null) {
                    sb.append(localList.get(i));
                }
            }
            processedData = sb.toString();
            myInternal.save("temporary_content.pcm", processedData);
            localList.clear();
            dialog.show();
        } catch (Exception e) {
            hideDialog();
            showToast("保存失敗,请重试");
            localList.clear();
            //关闭保存弹窗
//            dialog.dismiss();
            e.printStackTrace();
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WRITE_SUC://写入成功
                    if (btn.getText().equals("开始采集")) {
                        btn.setText("结束采集");
                    } else {
                        btn.setText("开始采集");
                    }
                    break;
                case WRITE_FAIL://写入失败

                    break;
                case SWITCH_OFF://断开
                    btn.setText("开始采集");
                    break;
                case ADD_LIST:
                    ArrayList<Float> list = new ArrayList<>();
                    list.addAll((List<Float>) msg.obj);
                    Log.e("TAG", "handleMessage: " + list.size());
                    ArrayList<Float> newList = new ArrayList<>();
                    for (int i = 0; i < list.size(); i += 40) {
                        newList.add(list.get(i));
                    }
                    addEcgView(newList);
                    pointList.clear();
                    break;
            }
        }
    };

    /**
     * 绘制心电图
     */
    private void addEcgView(final ArrayList<Float> list) {
        Log.d("TAG", "addEcgView: " + list.toString());
        final EcgView ecgView = new EcgView(GatherActivity.this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        ecgView.setMdata(list, gap_x);
        ecgView.setLayoutParams(params);
        llEcgContent.addView(ecgView);
    }


    /***
     * 获取 体位 场所 回调
     * @param bean
     */
    @Override
    public void getDictionarySuc(DictionaryBean bean) {
        String groupCode = "";
        if (bean.getResult().size() > 0) {
            groupCode = bean.getResult().get(0).getGroupCode();
        }
        if (groupCode.equals("SAMPLE_POSITION")) {
            positionList.addAll(bean.getResult());
        } else if (groupCode.equals("SAMPLE_COORDINATE")) {
            coordinateList.addAll(bean.getResult());
        } else if (groupCode.equals("SAMPLE_SITE")) {
            siteList.addAll(bean.getResult());
        }
    }

    // 采样率
    private int frequency = 8000;
    // 采样通道
    private int channelInConfig = AudioFormat.CHANNEL_IN_MONO;
    // 播放通道 单声道
    private int channelOutConfig = AudioFormat.CHANNEL_OUT_MONO;
    // 16位音频编码
    private int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
    // 录音缓存区
//    private byte[] bufferIn = null;

    // 存放录音缓存的队列
    private Queue<byte[]> bufferQueue = null;


    //同步录音播放
    private class RecordPlayingRunnable implements Runnable {

        @Override
        public void run() {
            tracker.play();
            while (true) {
                if (bluetoothGatt == null) {
                    return;
                }
                byte[] bufferOut = bufferQueue.poll();
                if (bufferOut != null && tracker != null) {
                    tracker.write(bufferOut, 0, bufferOut.length);
                }
                if (!isRecord) { //停止录音 弹出循环
                    return;
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            showFinish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("NewApi")
    private void showFinish() {

        if (btn.getText().equals("开始采集")) {
            finish();
        } else {
            showAlertDialog("", "确定停止采集吗?", new DialogUtil.DialogButtonClickListener() {
                @SuppressLint("NewApi")
                @Override
                public void onPositiveButtonClick(DialogInterface dialog) {
                    order = "ad00ad00";//结束录音
                    isRecord = false;
                    blueToothUtils.write(order);
                    tracker.stop();
                    finish();
                }

                @Override
                public void onNegativeButtonClick(DialogInterface dialog) {
                    dialog.dismiss();
                }
            });
        }
    }


    @SuppressLint("NewApi")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tracker != null) {
            tracker.release();
            tracker = null;
        }
        if (chronometer != null) {
            chronometer.stop();
        }
        if (pointTimer != null) {
            pointTimer.cancel();
            pointTimer = null;
        }
        if (moveTimer != null) {
            moveTimer.cancel();
            moveTimer = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        bluetoothGatt.disconnect();
    }


}
